package com.rachel.studyapp.fragment;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bm.library.PhotoView;
import com.rachel.commonsdk.glide.GlideManager;
import com.rachel.studyapp.R;
import com.rachel.studyapp.activity.BaseActivity;
import com.rachel.studyapp.activity.MainActivity;
import com.rachel.studyapp.activity.PermissionCallback;
import com.rachel.studyapp.activity.ScanZXingActivity;
import com.rachel.studyapp.activity.WebViewActivity;
import com.rachel.studyapp.adapter.CustomPopupWindow;
import com.rachel.studyapp.adapter.LBaseAdapter;
import com.rachel.studyapp.json.homejson.Footer;
import com.rachel.studyapp.json.homejson.HomeRoot;
import com.rachel.studyapp.mvp.ContractUtils;
import com.rachel.studyapp.mvp.present.HomePresent;
import com.rachel.studyapp.utils.ToolUtils;
import com.rachel.studyapp.view.CusViewPagerForHome;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zhengshaorui on 2017/5/23.
 */

public class HomeFragment extends BaseFragment<HomePresent> implements ContractUtils.IHomeView, View.OnClickListener {
    private static final String TAG = "zsr";
    /**
     * ui
     */
    private View mHomeView;
    private ImageView mLeftIcon;
    private TextView mSearchView;
    private ImageView mRightIcon;
    private ImageView mToolbarSearchIcon;
    private TextView mToolbarSearchText;
    private ListView mListView;

    /**
     * layout
     */
    private FrameLayout mSearchLy;
    private LinearLayout mMainContentLy;
    private RelativeLayout mLoadingLy;

    /**
     * others
     */
    private AnimationDrawable mLoadingAnim;
    private HomePresent mHomePresent;


    /**
     * data
     */
    private MainActivity mActivity;
    private List<View> mDatas = new ArrayList<>();
    private CusViewPagerForHome mCusViewPager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mActivity = (MainActivity) getActivity();
        if (mHomeView == null) {
            mHomeView = inflater.inflate(R.layout.fragment_home, container, false);
            initView(mHomeView);


        }

        return mHomeView;
    }



    @Override
    public HomePresent initPresent() {
        mHomePresent = new HomePresent(mActivity,this);
        return mHomePresent;
    }

    @Override
    public void onFailure(Object errorObj) {
        Toast.makeText(mActivity, "getjsonfail: "+errorObj.toString(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getJsonData(final HomeRoot root) {
        if (root != null){
            handleJsonData(root);
            ObjectAnimator animator = ObjectAnimator.ofFloat(mLoadingLy,"alpha",1f,0f);
            animator.setDuration(3000);
            animator.start();
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mLoadingLy.setVisibility(View.GONE);
                    mMainContentLy.setVisibility(View.VISIBLE);


                }
            });
        }
    }

    private void handleJsonData(HomeRoot root) {
        List<String> ads = new ArrayList<>();
        ads = root.getData().getHead().getAds();
        mCusViewPager = new CusViewPagerForHome(mActivity);
        if (!ads.isEmpty()) { //广告栏
            for (int i = 0; i < ads.size(); i++) {
                View view = LayoutInflater.from(mActivity).inflate(R.layout.banner_item, null);
                ImageView imageView = (ImageView) view.findViewById(R.id.viewpager_item_img);

                new GlideManager.Builder()
                        .setContext(mActivity)
                        .setTargetSource(ads.get(i))
                        .setImageView(imageView)
                        .builder();
                mDatas.add(view);
            }
            if (mDatas != null) {
                mCusViewPager.setDatas(mDatas);
            } else {
                Toast.makeText(mActivity, "加载失败", Toast.LENGTH_SHORT).show();
            }
        }
        //中间的图片
        List<String> mideles = new ArrayList<>();
        mideles = root.getData().getHead().getMiddle();
        View imagelyview = LayoutInflater.from(mActivity).inflate(R.layout.home_item_img,null);
        LinearLayout imagely = (LinearLayout) imagelyview.findViewById(R.id.home_image_ly);
        if (!mideles.isEmpty()){
            for (int i = 0; i < mideles.size(); i++) {
                final String url = mideles.get(i);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        0, ViewGroup.LayoutParams.MATCH_PARENT,1);
                if (i > 0) {
                    params.setMargins(ToolUtils.dip2px(mActivity, 5), 0, 0, 0);
                }
                ImageView iv = new ImageView(mActivity);
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                iv.setClickable(true);
                iv.setFocusable(true);
                iv.setLayoutParams(params);

                new GlideManager.Builder()
                        .setContext(mActivity)
                        .setTargetSource(url)
                        .setImageView(iv)
                        .builder();
                imagely.addView(iv);
                //点击放大
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CustomPopupWindow popupWindow = new CustomPopupWindow.Builder()
                                        .setContext(mActivity)
                                        .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                                        .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                                        .setContentView(R.layout.photoview_layout)
                                        .setOutSideCancel(true)
                                        .setFouse(true)
                                        .setAnimationStyle(R.style.popup_anmi)
                                        .builder()
                                        .showAtLocation(R.layout.fragment_home, Gravity.CENTER,0,0);

                        PhotoView photoView = (PhotoView) popupWindow.getItemView(R.id.photoview);
                        photoView.enable();
                        new GlideManager.Builder()
                                .setContext(mActivity)
                                .setTargetSource(url)
                                .setImageView(photoView)
                                .builder();
                    }
                });
            }
        }

      

        mListView.addHeaderView(mCusViewPager); //添加 viewpager

        View textView = LayoutInflater.from(mActivity).inflate(R.layout.home_item_course_text,null);
        mListView.addHeaderView(textView); //添加 item，即 中间的文字

        mListView.addHeaderView(imagelyview); //添加一行图片


        // 再来个中间
        List<Footer> mFooters = root.getData().getHead().getFooter();
        List<View> views = addDataToFooter(mFooters);
        for (View headerview : views) {
            mListView.addHeaderView(headerview);

        }
        LBaseAdapter adapter = new LBaseAdapter(mActivity,root.getData().getDatalist());
        adapter.setListview(mListView);
        mListView.setAdapter(adapter);


    }

    private List<View> addDataToFooter(List<Footer> datas) {
        List<View> views = new ArrayList<>();
        if (datas != null && datas.size() > 0){
            for (final Footer data : datas) {
                View view = LayoutInflater.from(mActivity).inflate(R.layout.home_item_recommand,null);
                TextView texttile = (TextView) view.findViewById(R.id.recommand_course_title);
                TextView textinfo = (TextView) view.findViewById(R.id.recommand_course_info);
                TextView textfrom = (TextView) view.findViewById(R.id.recommand_course_from);
                ImageView imageone = (ImageView) view.findViewById(R.id.recommand_course_img_one);
                ImageView imagetwo = (ImageView) view.findViewById(R.id.recommand_course_img_two);
                texttile.setText(data.getTitle());
                textinfo.setText(data.getInfo());
                textfrom.setText(data.getFrom());
                new GlideManager.Builder()
                        .setContext(mActivity)
                        .setTargetSource(data.getImageOne())
                        .setImageView(imageone)
                        .builder();
                new GlideManager.Builder()
                        .setContext(mActivity)
                        .setTargetSource(data.getImageTwo())
                        .setImageView(imagetwo)
                        .builder();
                views.add(view);
                view.setClickable(true);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(TAG, "onClick: ");
                        Intent intent = new Intent(mActivity,WebViewActivity.class);
                        intent.putExtra(ToolUtils.HTTPURL,data.getDestationUrl());
                        startActivity(intent);
                    }
                });
            }
        }

        return views;
    }


    private void initView(View view) {
        mLeftIcon = (ImageView) view.findViewById(R.id.left_icon);
        mToolbarSearchIcon = (ImageView) view.findViewById(R.id.toolbar_search_icon);
        mToolbarSearchText = (TextView) view.findViewById(R.id.toolbar_search_text);
        mSearchLy = (FrameLayout) view.findViewById(R.id.search_ly);
        mRightIcon = (ImageView) view.findViewById(R.id.right_icon);

        mLeftIcon.setVisibility(View.VISIBLE);
        mRightIcon.setVisibility(View.VISIBLE);
        mSearchLy.setVisibility(View.VISIBLE);

        mLeftIcon.setOnClickListener(this);
        mRightIcon.setOnClickListener(this);

        mLoadingLy = (RelativeLayout) view.findViewById(R.id.loading_ly);




        ImageView imageView = (ImageView) view.findViewById(R.id.loading_img);

        imageView.setBackgroundResource(R.drawable.main_loading_anim);


        mLoadingAnim = (AnimationDrawable) imageView.getBackground();
        mLoadingAnim.start();


        mMainContentLy = (LinearLayout) view.findViewById(R.id.main_content_ly);

        mListView = (ListView) view.findViewById(R.id.home_listview);




    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_icon:
                BaseActivity.checkPermissions(new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.VIBRATE}, new PermissionCallback() {
                    @Override
                    public void onGranted() {
                        startActivityForResult(new Intent(mActivity, ScanZXingActivity.class),
                                ToolUtils.SCAN_OPEN_QRCODE);
                       // ToolUtils.openFlash(mActivity,true);
                    }

                    @Override
                    public void onDenied(List<String> deniedPermissions) {
                        Toast.makeText(mActivity, "开启失败", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.right_icon:
                //ToolUtils.openFlash(mActivity,false);

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: "+requestCode);
        switch (requestCode){
            case ToolUtils.SCAN_OPEN_QRCODE:
                if (resultCode == RESULT_OK){
                    String result = data.getStringExtra(ToolUtils.SCAN_RESULT);
                    if (result.contains("http:") || result.contains("https:")){
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra(ToolUtils.HTTPURL,result);
                        startActivity(intent);
                    }else{
                        Toast.makeText(mActivity, "扫描到: "+result, Toast.LENGTH_SHORT).show();
                    }

                }
                break;

        }
    }
}
